import { ComponentWithStore } from "mobx-miniprogram-bindings";
import { userStore } from '../../stores/index'
import { reqCartList, reqUpdateChecked, reqCheckedAllStatus, reqAddCart, reqDelCartGoods } from '../api/cart'

import { debounce } from 'miniprogram-licia'
const computedBehavior = require('miniprogram-computed').behavior
ComponentWithStore({
  behaviors: [computedBehavior],
  // 让页面和store对象建立关联
  storeBindings: {
    store: userStore,
    fields: ['token']
  },
  //定义计算属性
  computed: {
    selectAllStatus(data) {
      return (
        data.cartList.length !== 0 && data.cartList.every((item) => item.isChecked === 1)
      )
    },
    totalPrice(data) {
      let totalPrice = 0
      data.cartList.forEach((item) => {
        if (item.isChecked === 1) {
          totalPrice += item.price * item.count
        }

      })
      return totalPrice
    }
  },
  // 组件的初始数据
  data: {
    cartList: [],
    emptyDes: '还没有添加商品，快去添加吧～'
  },


  // 组件的方法列表
  methods: {
    //获取购物车列表
    async getCartList() {
      const { token } = this.data
      if (!token) {
        this.setData({
          emptyDes: '您尚未登录，请先进行登录',
          cartList: []
        })
        return
      } else {
        const { code, data: cartList } = await reqCartList()
        if (code === 200) {
          this.setData({
            cartList,
            emptyDes: cartList.length === 0 && '还没有上商品，快去添加商品吧'
          })
        }
      }
    },
    //更新商品购买状态
    async updateChecked(event) {
      const { id, index } = event.target.dataset
      const { detail } = event
      const isChecked = detail ? 1 : 0
      const res = await reqUpdateChecked(id, isChecked)
      if (res.code === 200) {
        this.getCartList()
        this.setData({
          [`cartList[${index}].isChecked`]: isChecked
        })
      }
    },
    //全选按钮的逻辑操作
    async AllCheckedStatus(event) {
      const { detail } = event
      const AllChecked = detail ? 1 : 0

      const res = await reqCheckedAllStatus(AllChecked)
      if (res.code) {
        const newCartList = JSON.parse(JSON.stringify(this.data.cartList))
        newCartList.forEach((item) => item.isChecked = AllChecked)
        this.setData({
          cartList: newCartList
        })
      }
    },

    changeBuyNum: debounce(async function (event) {
      const newBuyNum = event.detail > 200 ? 200 : event.detail
      const { id, index, oldbuynum } = event.target.dataset
      const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
      const regRes = reg.test(newBuyNum)
      if (!regRes) {
        this.setData({
          [`cartList[${index}].count`]: oldbuynum
        })
        return
      }
      const disCount = newBuyNum - oldbuynum
      if (disCount === 0) return
      const res = await reqAddCart({ goodsId: id, count: disCount })
      if (res.code === 200) {
        this.setData({
          [`cartList[${index}].count`]: newBuyNum,
          [`cartList[${index}].isChecked`]: 1
        })
      }
    }, 500),
    async delCart(event) {
      const { id } = event.target.dataset

      const res = await reqDelCartGoods(id)
      if (res.code === 200) {

        this.getCartList()

      }
    },

    // 如果使用Component 方法构建页面 生命周期沟渠要写到methods里面
    toOrder() {
      if (this.data.totalPrice === 0) {
        wx.showToast({
          title: '请先添加商品',
          icon: 'none'

        })
        return
      }
      wx.navigateTo({
        url: '/modules/orderPayModule/pages/order/detail/detail'
      })
    },
    onShow() {
      this.getCartList()
    },

  }
})
